package com.system.controller;

import com.system.model.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by helloworld on 17-3-12.
 */
@Controller
public class LoginController {
    //返回 jsp 页面
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String login(){
        return "login/login";
    }


    @RequestMapping(value = "login", method = RequestMethod.POST)
    public ModelAndView login(SysUser user, HttpServletRequest request, Model model){
        try{
            Subject subject= SecurityUtils.getSubject();
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(), user.getPassword());
            subject.login(token);
            return new ModelAndView("redirect:/main/main.shtml");
        } catch (LockedAccountException lae) {
            lae.printStackTrace();
            model.addAttribute("msg", "账号已被禁用");
        } catch (AuthenticationException ae) {
            ae.printStackTrace();
            model.addAttribute("msg", "账号或密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("msg", "登录异常");
        }
        return new ModelAndView("login/login");
    }
}
